<template>
  <div class="params">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-alert
        title="注意:只允许为第三级分类设置相关参数!"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 联级选择器 -->
      <el-row>
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader
            v-model="selectedCateId"
            :options="cateList"
            :props="cascaderProps"
            @change="ParentCateChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleClickTabs">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="dialogVisible = true"
            >动态参数</el-button
          >
          <el-table :data="manyTableData" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="tagClose(index,scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editdialogAction(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeEditdialogAction(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="dialogVisible = true"
            >静态属性</el-button
          >
          <el-table :data="onlyTableData" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
               
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                   @close="tagClose(index,scope.row)"
                  >{{ item }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editdialogAction(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeEditdialogAction(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="dialogVisible"
      width="50%"
      @close="dialogClose"
    >
      <el-form
        :model="addForm"
        :rules="addrules"
        ref="addForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFormAction">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="editdialogClose"
    >
      <el-form
        :model="editForm"
        :rules="editrules"
        ref="editForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editFormAction">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from '@/axios/user'
export default {
  name: 'Params',
  data() {
    return {
      cateList: [], //商品所有数据
      selectedCateId: [], //选择的商品
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      activeName: 'many',
      //动态参数列表
      manyTableData: [],
      //静态参数列表
      onlyTableData: [],
      dialogVisible: false, //控制对话框的显示隐藏
      addForm: {
        attr_name: '',
      },
      addrules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      //修改
      editrules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      editForm: {
        attr_name: '',
      },
      editdialogVisible: false,
      inputVisible: false,
      inputValue: '',
    }
  },
  methods: {
    async getCateList() {
      const { data } = await axios.get('/categories')
      if (data.meta.status !== 200) {
        return this.$message.error(data.meta.msg)
      }
      this.cateList = data.data
      console.log(data)
    },
    ParentCateChange() {
      this.getParamsDta()
    },
    handleClickTabs(tab, event) {
      this.getParamsDta()
    },
    async getParamsDta() {
      if (this.selectedCateId.length !== 3) {
        return (this.selectedCateId = [])
      }
      const { data } = await axios.get(
        `/categories/${this.checkCateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )
      if (data.meta.status !== 200) {
        return this.$message.error(data.meta.msg)
      }

      data.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(data)
      if (this.activeName === 'many') {
        this.manyTableData = data.data
      } else {
        this.onlyTableData = data.data
      }
    },
    dialogClose() {
      this.$refs.addForm.resetFields()
    },
    addFormAction() {
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) return
        const { data } = await axios.post(
          `/categories/${this.checkCateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (data.meta.status !== 201) {
          return this.$message.error(data.meta.msg)
        }
        console.log(data)
        this.getParamsDta()
        this.dialogVisible = false
      })
    },
    async editdialogAction(id) {
      //console.log(id)
      const { data } = await axios.get(
        `categories/${this.checkCateId}/attributes/${id.attr_id}`,
        { params: { attr_sel: this.activeName } }
      )
      //console.log(data);
      if (data.meta.status !== 200) {
        return this.$message.error(data.meta.msg)
      }
      this.editForm = data.data
      this.editdialogVisible = true
    },
    editdialogClose() {},
    editFormAction() {
      console.log(1)
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) return
        const { data } = await axios.put(
          `/categories/${this.checkCateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (data.meta.status !== 200) {
          return this.$message.error(data.meta.msg)
        }
        this.getParamsDta()
        this.editdialogVisible = false
      })
    },
    async removeEditdialogAction(row) {
      const result = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      console.log(result)
      if (result === 'confirm') {
        const { data } = await axios.delete(
          `/categories/${this.checkCateId}/attributes/${row.attr_id}`
        )
        if (data.meta.status !== 200) {
          return this.$message.error(data.meta.msg)
        }
        this.$message.success(data.meta.msg)
        this.getParamsDta()
      }
    },
     handleInputConfirm(row) {
      if (row.inputValue.trim().length == 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
        this.saveTag(row)
    },
   async saveTag(row){
         const { data } = await axios.put(
        `/categories/${this.checkCateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )
      if(data.meta.status!==200){
         return  this.$message.error(data.meta.msg)
      }
      this.$message.success(data.meta.msg)
    },
    showInput(row) {
      row.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    tagClose(index,row){
        console.log(1);
        row.attr_vals.splice(index,1)
        this.saveTag(row)
    }
  },
  computed: {
    isDisabled() {
      if (this.selectedCateId.length !== 3) {
        return true
      } else {
        return false
      }
    },
    checkCateId() {
      if (this.selectedCateId.length === 3) {
        return this.selectedCateId[2]
      } else {
        return null
      }
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态参数'
    },
  },
  created() {
    this.getCateList()
  },
}
</script>

<style lang="scss" scoped>
.el-row {
  margin-top: 15px;
}
.el-tag {
  margin-right: 5px;
}
.input-new-tag {
  width: 120px;
}
</style>